package com.tubeonfire.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tubeonfire.entity.Channel;
import com.tubeonfire.service.ChannelService;
import com.tubeonfire.util.JavaCacheHandle;

public class ChannelController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "public, max-age=86400");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, 1);
		response.setHeader("Expires", cal.getTime().toString());
		// search by input key.
		try {
			String path = ((HttpServletRequest) request).getRequestURI();
			String[] splittedURI = path.split("/");
			if (splittedURI.length == 3) {
				String user = splittedURI[splittedURI.length - 1];
				user = URLDecoder.decode(user, "UTF8");
				System.out.println("Channel to search : " + user);
				Channel tubChannel = ChannelService.getByUserId(user);
				request.setAttribute("listCategory",
						JavaCacheHandle.getCategory());
				request.setAttribute("url", request.getRequestURL());
				request.setAttribute("listChannel",
						JavaCacheHandle.getChannels());
				request.setAttribute("result", tubChannel);
				request.setAttribute("user", user.replaceAll("\\+", " "));
				request.getRequestDispatcher("/channel_show.jsp").forward(request,
						response);
			} else {
				System.out.println("Error path.");
				response.sendRedirect("/home");
			}
		} catch (Exception e) {
			System.out.println("Exception.");
			e.printStackTrace();
			response.sendRedirect("/home");
		}
	}

}
